var theBody = document.body;
var path = safari.extension.baseURI;
OpenAjax.a11y.cache.updateLinkCache( parent.document );﻿  //updating links in cache
OpenAjax.a11y.cache.sortLinkCache( 'order' ); //sorting links in cache
var show = 0;
var firstClick = 1;


// Finds absolute x position of an object
function findPosX(obj)
  {
    var curleft = 0;
    if(obj.offsetParent)
        while(1) 
        {
          curleft += obj.offsetLeft;
          if(!obj.offsetParent)
            break;
          obj = obj.offsetParent;
        }
    else if(obj.x)
        curleft += obj.x;
    return curleft;
  }
  
// Finds absolute y position of object  
function findPosY(obj)
  {
    var curtop = 0;
    if(obj.offsetParent)
        while(1)
        {
          curtop += obj.offsetTop;
          if(!obj.offsetParent)
            break;
          obj = obj.offsetParent;
        }
    else if(obj.y)
        curtop += obj.y;
    return curtop;
  }


// adds icons to webpage next to links to provide accessibility information
function addIcons()
{    
	var linksLength =OpenAjax.a11y.cache.links.length; 
	for(var i=0; i < linksLength; i++)
	{
        var img = document.createElement("img");
        img.src = safari.extension.baseURI + "links.jpg";
		img.style.width ="15px";
		img.style.height="15px";
		img.className += (' inspectorlink' + i);
		OpenAjax.a11y.cache.links[i].node.appendChild(img);
    }
	
	
	// add qtip tooltip onto each icon displayed
	for(var j=0;j<linksLength; j++)
	{
	
	var currlink = OpenAjax.a11y.cache.links[j];
	$(".inspectorlink" + j).qtip({
	content: 'URL:' + currlink.href + '<br/>Text:' + currlink.accessible_text + '<br/>Position:' + findPosX(currlink.node) + ',' + findPosY(				  	currlink.node),
	show: 'mouseover',
	hide: 'mouseout',
	style: {
		name: 'dark', // preset style
		width: {min: Math.max(currlink.href.length,currlink.accessible_text.length)}
	},
	position:{ 
		adjust : {screen:true }
	}
})
	}
	
}

// loads jquery and then runs the dialog script
load = function() {
  load.getScript(path + 'jquery-ui/js/jquery-ui-1.8.11.custom.min.js');
  load.tryReady(0); // We will write this function later. It's responsible for waiting until jQuery loads before using it.
}		


// dynamically load any javascript file.
load.getScript = function(filename) {
  var script = document.createElement('script')
  script.setAttribute("type","text/javascript")
  script.setAttribute("src", filename)
  if (typeof script!="undefined")
  document.getElementsByTagName("head")[0].appendChild(script)
}


// wait till jquery is defined then run jquery ui dialog script
load.tryReady = function(time_elapsed) {
  // Continually polls to see if jQuery is loaded.
  if (typeof $ == "undefined") { // if jQuery isn't loaded yet...
    if (time_elapsed <= 5000) { // and we havn't given up trying...
      setTimeout("load.tryReady(" + (time_elapsed + 200) + ")", 200); // set a timer to check again in 200 ms.
    } else {
      alert("Timed out while loading jQuery.")
    }
  } else {
    // Any code to run after jQuery loads goes here!
    // for example:
   
		var script3 = document.createElement('script');
		script3.src = safari.extension.baseURI + 'jquery_dialog.js';
		script3.id = 'jquerydialog';
		document.body.appendChild(script3);
   
  }
}


	
function replyToMessage(aMessageEvent) {
	
   if (aMessageEvent.name === "hey") {
		//create an iframe to add to the end of page
		
		if(firstClick==1)
		{
		firstClick=0;
		show=1;
		var jquery = document.createElement('script');
		jquery.src = path + 'jquery-ui/js/jquery-1.5.1.min.js';
		document.getElementsByTagName("head")[0].appendChild(jquery);
		
		jquery.onload = function(){
		var jqueryui = document.createElement('script');
		jqueryui.src = path + 'jquery-ui/js/jquery-ui-1.8.11.custom.min.js';
		document.getElementsByTagName("head")[0].appendChild(jqueryui);
		
		jqueryui.onload = function(){
		var qtip = document.createElement('script');
		qtip.src = path + 'qtip/jquery.qtip-1.0.0-rc3.min.js';
		document.getElementsByTagName("head")[0].appendChild(qtip);		
		
		qtip.onload = function(){
		var script1 = document.createElement('script');
		script1.src = safari.extension.baseURI + 'oaa/scripts/cache.js';
		document.getElementsByTagName("head")[0].appendChild(script1);
		
		script1.onload = function(){
		var script2 = document.createElement('script');
		script2.src = safari.extension.baseURI + 'external.js';
		script2.id = 'external';
		document.body.appendChild(script2);
		
		script2.onload = function(){
			load();	
		}	
		}	
		}	
		}
		} }
		
		
		// if not first time then allow user to toggle display of the dialog. Is supposed to work this way but doesnt work currently.
		if(firstClick==0 && show==1)
		{
			$( "#dialog" ).dialog('close');
			show=0;
		}
		else
		{
			$("#dialog").dialog('open');
			show=1;
		}
		
		
	}
	else if(aMessageEvent.name === "showLinks") 
    {  	
        addIcons();
    }
	
	
		safari.self.tab.dispatchMessage("gotIt","Message acknowledged.");
}
// register for message events
safari.self.addEventListener("message", replyToMessage, false);	